//
//  OAuthVC.swift
//  kingWeiBo
//
//  Created by King on 15/9/11.
//  Copyright © 2015年 King. All rights reserved.
//

import UIKit
import SVProgressHUD

class OAuthVC: UIViewController, UIWebViewDelegate {
    
    lazy var OAuthwebView = UIWebView()
    
    
    override func loadView() {
        
        view = OAuthwebView
        OAuthwebView.delegate = self
        title = "新浪微博"
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "关闭", style: UIBarButtonItemStyle.Plain, target: self, action: "close")
    }
    
    
    
    func close(){
        SVProgressHUD.dismiss()
        dismissViewControllerAnimated(true, completion: nil)
    }
    
    //开始加载
    func webViewDidStartLoad(webView: UIWebView) {
        SVProgressHUD.show()
    }
    //完成加载
    func webViewDidFinishLoad(webView: UIWebView) {
        SVProgressHUD.dismiss()
    }
    /**
    1. 如果请求的 URL 包含 回调地址，需要判断参数，否则继续加载
    2. 如果请求参数中，包含 code，可以从请求的 url 中获得请求码
    */

    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        
        let urlString = request.URL!.absoluteString
        if !urlString.hasPrefix(NetWorkTool.shareTools.redirectUri) {
            return true
        }
        
        if let query = request.URL?.query where query.hasPrefix("code="){
            
            let code = query.substringFromIndex("code=".endIndex)
            print(code)
            
            loadAcessToke(code)
        }else{
            close()
        }
        return false
    }
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        OAuthwebView.loadRequest(NSURLRequest(URL: NetWorkTool.shareTools.oauthURL()))
    }
    
    
    
    
    func loadAcessToke(code: String){
        NetWorkTool.shareTools.loadAcessToken(code) { (result, error) -> () in
            if error != nil || result == nil{
                
               self.errorNet()
                return
            }
            
            
            userAccount(dict: result!).loadUserInfo({ (error) -> () in
                
                if error != nil{
                self.errorNet()
                    return
                }
                print("OK")
                NSNotificationCenter.defaultCenter().postNotificationName(KNTongzhi, object: false)
                self.close()
            })
      
        }
    }
    
    
    
    func errorNet(){
        
      SVProgressHUD.showInfoWithStatus("您的网络不给力")
        let when = dispatch_time(DISPATCH_TIME_NOW, Int64(1 * NSEC_PER_SEC))
        dispatch_after(when, dispatch_get_main_queue(), { () -> Void in
            self.close()
        })
    }
}
